package com.mkait.thief.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mkait.thief.domain.Complaint;
import com.mkait.thief.domain.ComplaintMessage;
import com.mkait.thief.mapper.ComplaintMessageMapper;
import com.mkait.thief.mapper.OrderMapper;
import com.mkait.thief.service.ComplaintService;
import com.mkait.thief.mapper.ComplaintMapper;
import com.mkait.thief.service.OrderService;
import com.mkait.thief.service.RefundService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
* @author VCOM
* @description 针对表【complaint】的数据库操作Service实现
* @createDate 2023-08-14 15:14:49
*/
@Service
@Slf4j
public class ComplaintServiceImpl extends ServiceImpl<ComplaintMapper, Complaint>
    implements ComplaintService{

    @Autowired
    private ComplaintMapper complaintMapper;

    @Autowired
    private ComplaintMessageMapper complaintMessageMapper;

    @Autowired
    private RefundService refundService;
    /**
     * 自动处理投诉
     */
    @Override
    public void handleComplaint() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTimeEnd = now.with(LocalTime.MAX).minusMinutes(10);
        LocalDateTime localDateTimeStart = now.with(LocalTime.MIN).plusMinutes(30);
        //如果当前时间在00：30以前则不执行
        if (now.isBefore(localDateTimeStart)){
            log.info("不超过当日00：30，不处理");
            return;
        }
        //如果当前时间在23：50以后则不执行
        if (now.isAfter(localDateTimeEnd)){
            log.info("已超过当日23：50，不再处理");
            return;
        }

        LambdaQueryWrapper<Complaint> complaintWrapper = new LambdaQueryWrapper<>();
        //complaintWrapper.eq(Complaint::getStatus, 0).ne(Complaint::getMerchantStatus,1).lt(Complaint::getCreateAt, (System.currentTimeMillis() - 86400000) / 1000);
        complaintWrapper.eq(Complaint::getStatus, 0).ne(Complaint::getMerchantStatus,1).lt(Complaint::getCreateAt, (System.currentTimeMillis() - 60000) / 1000);
        List<Complaint> complaints = complaintMapper.selectList(complaintWrapper);
        log.info("查询到" + complaints.size() + "条待自动处理投诉");
        for (Complaint complaint : complaints) {
            handleComplaint(complaint);
        }
    }

    @Override
    @Transactional
    public void refuseComplaint(String complaintId) {

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        String sessionUser = (String)request.getAttribute("sessionUser");

        //获取投诉订单
        LambdaQueryWrapper<Complaint> complaintWrapper = new LambdaQueryWrapper<>();
        complaintWrapper.eq(Complaint::getId, complaintId).eq(Complaint::getStatus, 0);
        Complaint complaint = complaintMapper.selectOne(complaintWrapper);
        if (complaint == null){
            return;
        }
        complaint.setMerchantStatus(0);

        //获取货源商户id
        String userId = complaint.getProxyParentUserId().equals(0) ? complaint.getUserId().toString() : complaint.getProxyParentUserId().toString();
        if (!userId.equals(sessionUser)){
            response.setStatus(403);
            return;
        }
        //更新投诉订单商家同意退款状态
        complaintMapper.update(complaint, complaintWrapper);

        //删除所有同意退款的投诉消息
        LambdaQueryWrapper<ComplaintMessage> complaintMessageWrapper = new LambdaQueryWrapper<>();
        complaintMessageWrapper.eq(ComplaintMessage::getTradeNo, complaint.getTradeNo()).eq(ComplaintMessage::getFrom, userId).like(ComplaintMessage::getContent, "已同意您的诉求，平台会尽快为您退款。");
        log.info("删除同意退款的投诉消息");
        complaintMessageMapper.delete(complaintMessageWrapper);
    }

    /**
     * 处理具体投诉
     * @param complaint
     */
    private void handleComplaint(Complaint complaint) {
        // 获取投诉订单
        String tradeNo = complaint.getTradeNo();
        //获取被投诉商家id
        Integer userId = complaint.getUserId();
        //获取商品真实商家id
        Integer proxyParentUserId = complaint.getProxyParentUserId();

        //判断是否为代理商品
        if (Integer.valueOf(0).equals(proxyParentUserId)){
            //创建获取商户消息wrapper
            LambdaQueryWrapper<ComplaintMessage> complaintMessageByShopUserWrapper = new LambdaQueryWrapper<>();
            complaintMessageByShopUserWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, userId);
            //获取商户消息列表
            List<ComplaintMessage> shopUserComplaintMessages = complaintMessageMapper.selectList(complaintMessageByShopUserWrapper);

            //判断是否存在商家回复，如果不存在则进行退款
            if (shopUserComplaintMessages == null || shopUserComplaintMessages.size() == 0){
                refundService.runRefund(complaint);
                return;
            }else {
                //判断商家是否同意退款，如果同意退款则进行退款
                LambdaQueryWrapper<ComplaintMessage> complaintMessageByShopUserAgreeRefundWrapper = new LambdaQueryWrapper<>();
                complaintMessageByShopUserAgreeRefundWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, userId).like(ComplaintMessage::getContent, "同意退款");
                complaintMessageByShopUserAgreeRefundWrapper.or();
                complaintMessageByShopUserAgreeRefundWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, userId).like(ComplaintMessage::getContent, "同意部分退款");
                complaintMessageByShopUserAgreeRefundWrapper.or();
                complaintMessageByShopUserAgreeRefundWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, userId).like(ComplaintMessage::getContent, "支持退款");
                int integer = complaintMessageMapper.selectCount(complaintMessageByShopUserAgreeRefundWrapper);
                if (integer > 0){
                    refundService.runRefund(complaint);
                    return;
                }
            }
        }else {
            //创建获取商户消息wrapper
            LambdaQueryWrapper<ComplaintMessage> complaintMessageByProxyParentUserWrapper = new LambdaQueryWrapper<>();
            complaintMessageByProxyParentUserWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, proxyParentUserId);
            //获取商户消息列表
            List<ComplaintMessage> proxyParentUserComplaintMessages = complaintMessageMapper.selectList(complaintMessageByProxyParentUserWrapper);

            //判断是否存在货源商家回复，如果不存在则判断代理商家是否同意退款，如果同意退款则进行退款
            if (proxyParentUserComplaintMessages == null || proxyParentUserComplaintMessages.size() == 0){
                LambdaQueryWrapper<ComplaintMessage> complaintMessageByShopUserAgreeRefundWrapper = new LambdaQueryWrapper<>();
                complaintMessageByShopUserAgreeRefundWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, userId).like(ComplaintMessage::getContent, "同意退款");
                complaintMessageByShopUserAgreeRefundWrapper.or();
                complaintMessageByShopUserAgreeRefundWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, userId).like(ComplaintMessage::getContent, "同意部分退款");
                complaintMessageByShopUserAgreeRefundWrapper.or();
                complaintMessageByShopUserAgreeRefundWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, userId).like(ComplaintMessage::getContent, "支持退款");
                int integer = complaintMessageMapper.selectCount(complaintMessageByShopUserAgreeRefundWrapper);
                if (integer > 0){
                    refundService.runRefund(complaint);
                    return;
                }
            }else {
                //判断货源商家是否同意退款，如果同意退款则进行退款
                LambdaQueryWrapper<ComplaintMessage> complaintMessageByProxyParentUserAgreeRefundWrapper = new LambdaQueryWrapper<>();
                complaintMessageByProxyParentUserAgreeRefundWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, proxyParentUserId).like(ComplaintMessage::getContent, "同意退款");
                complaintMessageByProxyParentUserAgreeRefundWrapper.or();
                complaintMessageByProxyParentUserAgreeRefundWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, proxyParentUserId).like(ComplaintMessage::getContent, "同意部分退款");
                complaintMessageByProxyParentUserAgreeRefundWrapper.or();
                complaintMessageByProxyParentUserAgreeRefundWrapper.eq(ComplaintMessage::getTradeNo, tradeNo).eq(ComplaintMessage::getFrom, proxyParentUserId).like(ComplaintMessage::getContent, "支持退款");
                int integer = complaintMessageMapper.selectCount(complaintMessageByProxyParentUserAgreeRefundWrapper);
                if (integer > 0){
                    refundService.runRefund(complaint);
                    return;
                }
            }
        }

        //如果上方逻辑全部未进行退款操作，则进行拒绝退款
        refundService.refuseRefund(complaint);
    }
}




